package com.chainyoung.component_tmtrade.ui.activity;


import android.content.DialogInterface;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.chainyoung.common.appcommon.entity.UploadFile;
import com.chainyoung.common.base.BaseActivity;
import com.chainyoung.common.constant.CommonStringConstants;
import com.chainyoung.common.constant.LibConstant;
import com.chainyoung.common.di.AppComponent;
import com.chainyoung.common.imageloader.ImageLoader;
import com.chainyoung.common.imageloader.glide.GlideImageConfig;
import com.chainyoung.common.utils.AppUtils;
import com.chainyoung.common.utils.CommonUtil;
import com.chainyoung.common.utils.SPUtil;
import com.chainyoung.common.utils.ToastUtil;
import com.chainyoung.common.utils.Utils;
import com.chainyoung.common.view.kprogresshud.KProgressHUD;
import com.chainyoung.component_tmtrade.R;
import com.chainyoung.component_tmtrade.R2;
import com.chainyoung.component_tmtrade.bean.OrderDetail;
import com.chainyoung.component_tmtrade.constant.StringConstant;
import com.chainyoung.component_tmtrade.di.component.DaggerTradeFiatCurrencyActivityComponent;
import com.chainyoung.component_tmtrade.di.module.TradeFiatCurrencyActivityModule;
import com.chainyoung.component_tmtrade.ui.mvp.contract.TradeFiatCurrencyOrderDetailContract;
import com.chainyoung.component_tmtrade.ui.mvp.presenter.TradeFiatCurrencyOrderDetailPresenter;
import com.chainyoung.router.RouterConstants;
import com.chainyoung.router.RouterUtils;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.OnClick;

import static com.chainyoung.common.constant.CommonStringConstants.URL;

import static com.chainyoung.component_tmtrade.ui.fragment.fiatcurrency.TradeFiatCurrencyMainFragment.TYPE_SELL;
import static com.chainyoung.router.RouterConstants.PATH_ORDER_DETAIl;


/**
 * 买和卖共用一个页面
 */


@Route(path = PATH_ORDER_DETAIl)
public class TradeFiatCurrencyOrderDetailActivity extends BaseActivity<TradeFiatCurrencyOrderDetailPresenter> implements TradeFiatCurrencyOrderDetailContract.View {


    @BindView(R2.id.tv_order_no)
    TextView tvOrderNo;
    @BindView(R2.id.tv_buy_price)
    TextView tvBuyPrice;
    @BindView(R2.id.tv_buy_num)
    TextView tvBuyNum;
    @BindView(R2.id.tv_type_bit)
    TextView tvTypeBit;
    @BindView(R2.id.tv_total_money)
    TextView tvTotalMoney;//合计金额
    @BindView(R2.id.iv_ali_code)
    ImageView ivAliCode;
    @BindView(R2.id.iv_wx_code)
    ImageView ivWxCode;
    @BindView(R2.id.tv_show_bank_info)
    TextView tvShowBankInfo;
    @BindView(R2.id.tv_bank_no)
    TextView tvBankNo;
    @BindView(R2.id.tv_bank_name)
    TextView tvBankName;
    @BindView(R2.id.tv_bank_addr)
    TextView tvBankAddr;
    @BindView(R2.id.ll_bank_info)
    RelativeLayout llBankInfo;
    @BindView(R2.id.tv_remark_no)
    TextView tvRemarkNo;
    @BindView(R2.id.tv_remark_info)
    TextView tvRemarkInfo;
    @BindView(R2.id.title_pay_img)
    TextView titlePayImg;
    @BindView(R2.id.tv_pay_img_info)
    TextView tvPayImgInfo;
    @BindView(R2.id.iv_pay_img)
    ImageView ivPayImg;
    @BindView(R2.id.btn_1)
    TextView btn1;
    @BindView(R2.id.btn_2)
    TextView btn2;
    @BindView(R2.id.refresh_layout)
    SmartRefreshLayout refreshLayout;
    @BindView(R2.id.tv_time)
    TextView tvTime;
    @BindView(R2.id.txt_buy_amount)
    TextView txtBuyAmount;
    @BindView(R2.id.txt_buy_price)
    TextView txtBuyPrice;
    @BindView(R2.id.tv_owner_name)
    TextView tvOwnerName;

    private String orderId;

    private int status;
    private ImageLoader imageLoader;
    private OrderDetail orderDetail;
    private HashMap<Integer, OrderDetail.BankMsgBean> accountMap = new HashMap<>();
    private String payImg;//付款截图
    private String title;
    SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd HH:mm");


    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerTradeFiatCurrencyActivityComponent.builder()
                .appComponent(appComponent)
                .tradeFiatCurrencyActivityModule(new TradeFiatCurrencyActivityModule(this))
                .build()
                .inject(this);
    }


    @Override
    protected void initUI() {
        orderId = getIntent().getStringExtra(StringConstant.ID);
        showAndSetBarRightText(R.string.tmtrade_contact_customer_service);
        imageLoader = Utils.getAppComponent().imageLoader();
        refreshLayout.setEnableLoadMore(false);

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                getOrderDetail();
            }
        });

        refreshLayout.setPrimaryColorsId(R.color._4486f5, R.color.white);

    }

    @Override
    public void onRightTxtClicked(View v) {
        super.onRightTxtClicked(v);
        RouterUtils.getInstance()
                .build(RouterConstants.PATH_CHAT_ROOM)
                .withString(URL, CommonUtil.getUserInfo().getH5_chat_url())
                .navigation();
    }

    @Override
    protected void initData() {
         getOrderDetail();

    }

    private void getOrderDetail() {
        TreeMap<String, Object> map = new TreeMap<>();
        map.put("token", SPUtil.getString(LibConstant.TOKEN));
        map.put("id", orderId);
        mPresenter.getOrderDetail(map);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.tmtrade_activity_fiat_currency_order_detail;
    }


    @Override
    public void onGetOrderDetailSuccess(OrderDetail data) {
        refreshLayout.finishRefresh();
        status = data.getStatus();
        setCurrentTitle(getStautsStr(status) + getString(R.string.tmtrade_order));
        orderDetail = data;
        tvOrderNo.setText(data.getOrderno());
        tvBuyPrice.setText(String.format("%s", new BigDecimal(data.getPrice_cny()).setScale(2, BigDecimal.ROUND_DOWN)));
        tvBuyNum.setText(data.getNum());
        tvTotalMoney.setText(CommonStringConstants.RMB + data.getMum_cny());
        tvTypeBit.setText(data.getCoin());
        tvRemarkNo.setText(data.getReference_no());
        String time = dfs.format(new Date((data.getAddtime() * 1000)));
        tvTime.setText(time);

        accountMap.clear();
        if (data.getBank_msg() != null && !data.getBank_msg().isEmpty()) {
            for (OrderDetail.BankMsgBean item : data.getBank_msg()) {
                accountMap.put(item.getType(), item);
            }
        }
        if (data.getType() == TYPE_SELL) {
            txtBuyAmount.setText(R.string.tmtrade_sell_out_num);
            txtBuyPrice.setText(R.string.tmtrade_evaluate_sell);
        }


        switch (data.getStatus()) {
            case 0:
                //待付款
            case 10:
                //待付款
                btn1.setText(getString(R.string.tmtrade_i_payed));
                btn2.setVisibility(View.VISIBLE);
                titlePayImg.setText(R.string.tmtrade_upload_pay_img);
                tvPayImgInfo.setText(R.string.tmtrade_pls_upload_pay_img_notice);
                break;
            case 7:
                //待放币
                btn1.setText("确认放币");
                // TODO: 2018/8/10 haspaid gray unable
                if (!orderDetail.isHas_paid()) {
                    btn1.setEnabled(false);
                    btn1.setBackgroundResource(R.drawable.shape_gray_radius);
                    btn1.setTextColor(ContextCompat.getColor(mContext, R.color._000000));
                } else {
                    btn1.setEnabled(true);
                    btn1.setBackgroundResource(R.drawable.shape_blue_radius);
                    btn1.setTextColor(ContextCompat.getColor(mContext, R.color.white));
                }
                btn2.setVisibility(View.GONE);
                titlePayImg.setText(R.string.tmtrade_pay_img);
                imageLoader.loadImage(mContext,
                        GlideImageConfig
                                .builder()
                                .url(data.getVoucherimg())
                                .imagerView(ivPayImg)
                                .build());
                tvPayImgInfo.setText(R.string.tmtrade_pls_check_pay_img);
                tvRemarkInfo.setText(R.string.tmtrade_pls_check_remark_info);
                txtBuyAmount.setText(R.string.tmtrade_sell_out_num);
                txtBuyPrice.setText(R.string.tmtrade_evaluate_sell);

                break;
            case 8:
            case 9:
                // 隐藏按钮
                btn1.setVisibility(View.GONE);
                btn2.setVisibility(View.GONE);
                tvPayImgInfo.setText(R.string.tmtrade_pls_check_pay_img);
                tvRemarkInfo.setText(R.string.tmtrade_pls_check_remark_info);
            default:
                //btn1.setText("前往钱包");
                btn1.setVisibility(View.GONE);
                btn2.setVisibility(View.GONE);
                imageLoader.loadImage(mContext,
                        GlideImageConfig
                                .builder()
                                .url(data.getVoucherimg())
                                .imagerView(ivPayImg)
                                .build());
        }

    }

    @Override
    public void onGetOrderDetailFailed() {
        refreshLayout.finishRefresh();
    }

    private String getStautsStr(int status) {
        switch (status) {
            case 0:
            case 10:
                return mContext.getString(R.string.tmtrade_order_wait_for_pay);
            case 1:
                return mContext.getString(R.string.tmtrade_order_finished);
            case 2:
            case 3:
            case 4:
                return mContext.getString(R.string.tmtrade_order_closed);
            case 7:
                return mContext.getString(R.string.tmtrade_order_already_payed);
            case 8:
                return mContext.getString(R.string.tmtrade_wait_for_recieve);
            case 9:
                return mContext.getString(R.string.tmtrade_wait_recieve);
        }
        return null;
    }

    @Override
    public void onCancelOrderSuccess(String data) {
        ToastUtil.showToast(data);
        getOrderDetail();
    }

    @Override
    public void onConfirmPayOrder(String data) {
        ToastUtil.showToast(data);
        getOrderDetail();
    }

    @Override
    public void onConfirmRelease(String data) {
        KProgressHUD.create(this)
                .setCustomView(mContext, R.drawable.tips_correct)
                .setLabel(getString(R.string.tmtrade_success))
                .show().setDuration(1500);
        getOrderDetail();
    }


    @OnClick(R2.id.iv_ali_code)
    void showAliCode() {
        if (orderDetail == null) {
            return;
        }
        if (accountMap.containsKey(2)) {
            Intent intent = new Intent(mContext, ShowQrCodeActivity.class);
            intent.putExtra("title", getString(R.string.tmtrade_check_qrcode));
            intent.putExtra("img", accountMap.get(2).getReceivables_code());
            mContext.startActivity(intent);
        } else {
            KProgressHUD.create(this)
                    .setCustomView(mContext, R.drawable.tips_error)
                    .setLabel(getString(R.string.tmtrade_no_ali_code))
                    .show().setDuration(1500);
        }

    }

    @OnClick(R2.id.iv_wx_code)
    void showWxCode() {
        if (orderDetail == null) {
            return;
        }
        if (accountMap.containsKey(3)) {
            Intent intent = new Intent(mContext, ShowQrCodeActivity.class);
            intent.putExtra("title", getString(R.string.tmtrade_check_qrcode));
            intent.putExtra("img", accountMap.get(3).getReceivables_code());
            mContext.startActivity(intent);
        } else {
            KProgressHUD.create(this)
                    .setCustomView(mContext, R.drawable.tips_error)
                    .setLabel(getString(R.string.tmtrade_no_wx_code))
                    .show().setDuration(1500);
        }
    }


    private boolean isBankInfoShow = false;

    @OnClick(R2.id.tv_show_bank_info)
    void showBankInfo() {
        if (orderDetail == null) {
            return;
        }
        if (accountMap.containsKey(1)) {
            llBankInfo.setVisibility(isBankInfoShow ? View.GONE : View.VISIBLE);
            tvShowBankInfo.setText(isBankInfoShow ? "展开" : "收起");
            tvShowBankInfo.setCompoundDrawablesRelativeWithIntrinsicBounds(0, 0, isBankInfoShow ? R.mipmap.ic_triangle_down : R.mipmap.ic_triangle_up, 0);
            isBankInfoShow = !isBankInfoShow;
            OrderDetail.BankMsgBean data = accountMap.get(1);
            tvBankNo.setText(data.getBankcard());
            tvBankName.setText(data.getBank());
            tvBankAddr.setText(data.getBankaddr());
            tvOwnerName.setText(data.getName());
        } else {
            KProgressHUD.create(this)
                    .setCustomView(mContext, R.drawable.tips_error)
                    .setLabel(getString(R.string.tmtrade_no_bank_card))
                    .show().setDuration(1500);
        }
    }

    @OnClick(R2.id.btn_1)
    void onClickBtn1() {
        switch (status) {
            case 0:
            case 10:
                //确认付款
                if (selectImgs.isEmpty()) {
                    ToastUtil.showToast(getString(R.string.tmtrade_pls_upload_pay_img));
                    return;
                }
                AlertDialog.Builder builder2 = new AlertDialog.Builder(mContext);
                builder2.setMessage(R.string.tmtrade_confirm_pay_order)
                        .setPositiveButton(mContext.getString(R.string.yes), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                upLoadPayImg();
                                dialog.dismiss();
                            }
                        })
                        .setNegativeButton(mContext.getString(R.string.no), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });

                builder2.create();
                builder2.show();
                break;
            case 7://待放币
                AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                builder.setMessage(R.string.tmtrade_confirm_release_coin)
                        .setPositiveButton(mContext.getString(R.string.yes), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                onConfirmRelease();
                                dialog.dismiss();
                            }
                        })
                        .setNegativeButton(mContext.getString(R.string.no), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });

                builder.create();
                builder.show();

                break;
            default:
                //前往钱包
                RouterUtils.getInstance()
                        .build(RouterConstants.PATH_MAIN_MARKET_ACTIVITY)
                        .withInt("page", 4)
                        .navigation(this);


        }
    }

    private void upLoadPayImg() {
        mPresenter.upLoadPayImg(selectImgs.get(0), 3);//上传收款凭证
    }


    @Override
    public void onUploadPayImg(UploadFile data) {
        payImg = data.getPreview();
        onConfirmPay();
    }

    private void onConfirmPay() {
        TreeMap<String, Object> map = new TreeMap<>();
        map.put("token", SPUtil.getString(LibConstant.TOKEN));
        map.put("id", orderId);
        map.put("voucherimg", payImg);
        mPresenter.confirmPayed(map);

    }

    private void onConfirmRelease() {
        TreeMap<String, Object> map = new TreeMap<>();
        map.put("token", SPUtil.getString(LibConstant.TOKEN));
        map.put("id", orderId);
        mPresenter.confirmRelease(map);
    }

    @OnClick(R2.id.btn_2)
    void onClickBtn2() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setMessage(R.string.tmtrade_confirm_cancel_order)
                .setPositiveButton(mContext.getString(R.string.yes), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        TreeMap<String, Object> map = new TreeMap<>();
                        map.put("token", SPUtil.getString(LibConstant.TOKEN));
                        map.put("id", orderId);
                        mPresenter.cancelOrder(map);
                        dialog.dismiss();
                    }
                })
                .setNegativeButton(mContext.getString(R.string.no), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });

        builder.create();
        builder.show();

    }

    @OnClick(R2.id.iv_pay_img)
    void onPayImg() {
        switch (status) {
            case 0:
            case 10:
                //待付款 上传截图
                PictureSelector.create(this)
                        .openGallery(PictureMimeType.ofImage())
                        .maxSelectNum(1)
                        .enableCrop(true)
                        .glideOverride(160, 160)
                        .compress(true)
                        .compressSavePath(AppUtils.getImagePath())
                        .freeStyleCropEnabled(true)
                        .minimumCompressSize(100)
                        .forResult(PictureConfig.CHOOSE_REQUEST);
                break;
            default:
                //其他 查看截图
                if (TextUtils.isEmpty(orderDetail.getVoucherimg())) {
                    KProgressHUD.create(this)
                            .setCustomView(mContext, R.drawable.tips_error)
                            .setLabel(getString(R.string.tmtrade_pay_img_not_upload))
                            .show().setDuration(1500);
                } else {
                    Intent intent = new Intent(mContext, ShowQrCodeActivity.class);
                    intent.putExtra("title", "查看图片");
                    intent.putExtra("img", orderDetail.getVoucherimg());
                    mContext.startActivity(intent);
                }
        }
    }


    private List<String> selectImgs = new ArrayList<>();

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，已取压缩路径为准，因为是先裁剪后压缩的
                    selectImgs.clear();
                    for (LocalMedia media : selectList) {
                        selectImgs.add(media.getCompressPath());
                        Log.i("图片-----》", media.getCompressPath());
                    }
                    if (!selectImgs.isEmpty()) {
                        Glide.with(mContext).load(selectImgs.get(0)).apply(RequestOptions.placeholderOf(R.mipmap.ic_default).error(R.mipmap.ic_default)).into(ivPayImg);
                    }
                    break;
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        //getOrderDetail();
    }
}
